package com.oncecloud.devops.service.sample.core.impl;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.model.JobWithDetails;
import com.oncecloud.devops.service.sample.bean.HttpClient;
import com.oncecloud.devops.service.sample.bean.RequestCommand;
import com.oncecloud.devops.service.sample.bean.Result;
import com.oncecloud.devops.service.sample.bean.SSH;
import com.oncecloud.devops.service.sample.common.CiHost;
import com.oncecloud.devops.service.sample.common.GitLab;
import com.oncecloud.devops.service.sample.common.JenkinsItem;
import com.oncecloud.devops.service.sample.config.JenkinsJobXmls;
import com.oncecloud.devops.service.sample.core.CiCore;
@Component
public class CiCoreImpl implements CiCore{
	private static final Logger LOGGER = Logger.getLogger(CiCoreImpl.class);
	private static JenkinsServer jenkinsServer;
	@Override
	public Result getGitProjects(GitLab gitLab, String private_token) {
		Result check_gitlab = checkGitLabUrl(gitLab);
		if(!check_gitlab.isSuccess()){
			return check_gitlab;
		}
		HttpClient httpClient = new HttpClient();
		String url = RequestCommand.getProjectsCommand(gitLab);
		Map<String, String> param = new HashMap<>();
		if(StringUtils.isNotEmpty(private_token)){
			param.put("private_token", private_token);
		}
		String result = httpClient.get(param, url);
		Result info = checkResult(result);
		if(StringUtils.isNotEmpty(result)&&info.isSuccess()){
			LOGGER.info("get projects success");
			return new Result(true,result,"get projects success");
		}
		return info;
	}

	@Override
	public Result getGitSingleProject(GitLab gitLab, String private_token) {
		Result check_gitlab = checkGitLabUrl(gitLab);
		if(!check_gitlab.isSuccess()){
			return check_gitlab;
		}
		HttpClient httpClient = new HttpClient();
		String url = RequestCommand.getSingleProjectCommand(gitLab);
		Map<String, String> param = new HashMap<>();
		if(StringUtils.isNotEmpty(private_token)){
			param.put("private_token", private_token);
		}
		String result = httpClient.get(param, url);
		Result info = checkResult(result);
		if(StringUtils.isNotEmpty(result)&&info.isSuccess()){
			LOGGER.info("get project success");
			return new Result(true,result,"get project success");
		}
		return info;
	}

	@Override
	public Result getGitProjectBranches(GitLab gitLab, String private_token) {
		Result check_gitlab = checkGitLabUrl(gitLab);
		if(!check_gitlab.isSuccess()){
			return check_gitlab;
		}
		HttpClient httpClient = new HttpClient();
		String url = RequestCommand.getProjectBranchsCommand(gitLab);
		Map<String, String> param = new HashMap<>();
		if(StringUtils.isNotEmpty(private_token)){
			param.put("private_token", private_token);
		}
		String result = httpClient.get(param, url);
		Result info = checkResult(result);
		if(StringUtils.isNotEmpty(result)&&info.isSuccess()){
			LOGGER.info("get branches success");
			return new Result(true,result,"get branches success");
		}
		return info;
	}

	@Override
	public Result getGitProjectSingleBranch(GitLab gitLab, String private_token,
			String branch_name) {
		Result check_gitlab = checkGitLabUrl(gitLab);
		if(!check_gitlab.isSuccess()){
			return check_gitlab;
		}
		HttpClient httpClient = new HttpClient();
		String url = RequestCommand.getProjectSingleBranchCommand(gitLab);
		Map<String, String> param = new HashMap<>();
		if(StringUtils.isNotEmpty(private_token)){
			param.put("private_token", private_token);
		}
		String result = httpClient.get(param, url);
		Result info = checkResult(result);
		if(StringUtils.isNotEmpty(result)&&info.isSuccess()){
			LOGGER.info("get branch success");
			return new Result(true,result,"get branch success");
		}
		return info;
	}

	@Override
	public Result getGitProjectHooks(GitLab gitLab, String private_token) {
		return null;
	}

	@Override
	public Result getGitProjectSingleHook(GitLab gitLab, String private_token, String hookId) {
		return null;
	}

	@Override
	public Result createGitProjectHook(GitLab gitLab, String private_token, String hookUrl,
			Map<String, Boolean> events) {
		return null;
	}

	@Override
	public Result deleteGitProjectHook(GitLab gitLab, String private_token) {
		return null;
	}

	@Override
	public Result gitClone(CiHost ciHost, String sourcePath, String branch, String gitAddress) {
		String command = RequestCommand.gitCloneCommand(gitAddress,sourcePath, branch);
		Result result = SSH.stdoutConnection(ciHost.getHost_ip(), ciHost.getHost_user(), ciHost.getHost_pwd(),command);
		return result;
	}

	@Override
	public Result sonarSourceScanner(CiHost ciHost, String sourcePath) {
		String command = RequestCommand.sonarAnalysisCommand(sourcePath);
		Result result = SSH.stdoutConnection(ciHost.getHost_ip(), ciHost.getHost_user(), ciHost.getHost_pwd(),command);
		return result;
	}

	@Override
	public Result mavenUnitTest(CiHost ciHost, String sourcePath) {
		String command = RequestCommand.unitTestCommand(sourcePath);
		Result result = SSH.stdoutConnection(ciHost.getHost_ip(), ciHost.getHost_user(), ciHost.getHost_pwd(),command);
		return result;
	}

	@Override
	public Result mavenSourcePackage(CiHost ciHost, String sourcePath) {
		String command = RequestCommand.mvnPackageCommand(sourcePath);
		Result result = SSH.stdoutConnection(ciHost.getHost_ip(), ciHost.getHost_user(), ciHost.getHost_pwd(),command);
		return result;
	}

	@Override
	public Result createJenkinsProject(JenkinsItem jenkinsItem) throws URISyntaxException {
		Result result = new Result();
		//初始化jenkins server
		jenkinsServer = new JenkinsServer(new URI(jenkinsItem.getJenkins_url()), jenkinsItem.getJenkins_user(), jenkinsItem.getJenkins_pwd());
		try {
			JobWithDetails jobWithDetails = jenkinsServer.getJob(jenkinsItem.getItem_name());
			if(null!=jobWithDetails){
				result.setSuccess(false);
				result.setMessage("A job already exists with the name "+jenkinsItem.getItem_name());
				return result;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		String jobXml= JenkinsJobXmls.getJobxml(jenkinsItem);
		try {
			//创建job
			jenkinsServer.createJob(jenkinsItem.getItem_name(), jobXml);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new Result(true, "create job "+jenkinsItem.getItem_name()+" success");
	}

	private Result checkResult(String result){
		if(StringUtils.isEmpty(result)){
			return new Result(false, "result is null");
		}
		if(result.contains("404 Project Not Found")){
			return new Result(false, "404 Project Not Found");
		}
		if(result.contains("404 Not Found")){
			return new Result(false, "404 Not Found");
		}
		if(result.contains("404 Branch Not Found")){
			return new Result(false, "404 Branch Not Found");
		}
		if(result.contains("404 Not Found")){
			return new Result(false, "404 Not Found");
		}
		return new Result(true, "");
	}
	/**
	 * 检查gitlab仓库信息
	 * @param gitLab
	 * @return
	 */
	private Result checkGitLabUrl(GitLab gitLab){
		if(StringUtils.isEmpty(gitLab.getHttp_protocol())){
			LOGGER.error("request protocol is needed");
			return new Result(false, "request protocol is needed");
		}else if(StringUtils.isEmpty(gitLab.getGitLab_url())){
			LOGGER.error("request gitlab address is needed");
			return new Result(false, "request gitlab address is needed");
		}else if(StringUtils.isEmpty(gitLab.getGitLab_port())){
			LOGGER.error("request gitlab port is needed");
			return new Result(false, "request gitlab port is needed");
		}else if(StringUtils.isEmpty(gitLab.getHttp_protocol())){
			LOGGER.error("request gitlab version is needed");
			return new Result(false, "request gitlab version is needed");
		}
		return new Result(true, "");
	}
}
